package com.axend.aerosense.common.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.axend.aerosense.common.util.SSlUtil;
import com.blankj.utilcode.util.LogUtils;
import com.axend.aerosense.common.R;
import com.axend.aerosense.common.databinding.CommonActivityWebBinding;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;

public class WebActivity extends AppCompatActivity {
    public final static String URL  = "URL";  //URL
    public final static String TITLE  = "TITLE";  //标题
    public final static String REPORT_KEY = "REPORT_KEY";  //睡眠报告或ADL请求密匙
    /**
     * 访问路径URL中如果含有这些字符串，则关闭工具栏
     * 注意：多个字符串请使用“-”符号分割
     */
    private final static String SHOW_TOOLBAR_PAHT =
                    "EndUserAgreement.html" +   //用户协议
                    "-PrivacyPolicy.html";      //隐私政策
//            "/title/" +
//            "-/showDay/" +
//            "-/html/Help.html" +  //帮助和反馈
//            "-/Ecarts.html" +     //ADL报告
//            "-/Ecarts_ADL.html" +     //ADL报告
//            "-/Ecarts_Sleep.html" +     //睡眠报告
//            "-/instruction.html";


    private CommonActivityWebBinding viewDataBinding;
    private WebView webView = null;
    private String title = "";

    private Handler handler;
    private int retryCount = 3;
    private String url;
    private String reportKey;


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if (null != intent){
            url = intent.getStringExtra(URL);
            title = intent.getStringExtra(TITLE);
            reportKey = intent.getStringExtra(REPORT_KEY);
        }
        if(TextUtils.isEmpty(url)){
            finish();
            return;
        }

        handler = new Handler(getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0){
//                    if(null != msg.obj){
//                        ToastUtils.showShort((String) msg.obj);
//                    }
                    finish();
                }
            }
        };

        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.common_activity_web);
//        webView.loadUrl(url);
        setSupportActionBar(viewDataBinding.commonToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        //是否关闭ToolBar
        boolean isShow = false;
        String[] split = SHOW_TOOLBAR_PAHT.split("-");
        for (String str : split){
            if(url.contains(str)){
                LogUtils.d(url, "显示ToolBar");
                isShow = true;
                break;
            }
        }
        viewDataBinding.commonToolbar.setVisibility(isShow ? View.VISIBLE : View.GONE);

        webView = new WebView(this);
        viewDataBinding.commonContent.addView(webView,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置不出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        // 使用了https头，而h5页面中使用了http头，解决的问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // WebView调试
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            webView.setWebContentsDebuggingEnabled(true);
//        }
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setAllowFileAccess(true);

        if(Build.VERSION.SDK_INT < 33){
            String appCachePath = getApplication().getCacheDir().getAbsolutePath();
            webView.getSettings().setAppCacheEnabled(true);
            webView.getSettings().setAppCachePath(appCachePath);
        }
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebViewClient(new WebViewClient(){
            private SSLContext sslContext = SSlUtil.getSSLContext(getApplicationContext());

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // webview 自行处理 跳转
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (isSSLCertOk(error.getCertificate(), "d2e57743d5a3ae1be1bd23b5421c3182ad2026cba0f6b64e77de484098302b2a")) {
//                    Log.e("__MY__", "1212:1");
                    handler.proceed();
                } else {
                    handler.cancel();
                }
            }
//            @Override
//            public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
//                return processRequest(Uri.parse(url));
//            }
//
//            @Override
//            public WebResourceResponse shouldInterceptRequest(final WebView view, WebResourceRequest interceptedRequest) {
//                return processRequest(interceptedRequest.getUrl());
//            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                super.onReceivedError(view, request, error);
//                Log.e("__MY__", "1212:" + request.getUrl());
//                request.
                if(retryCount > 0){
                    retryCount --;
                    webView.reload();
                }else{
                    super.onReceivedError(view, request, error);
                }

            }

//            private WebResourceResponse processRequest(Uri uri) {
//                Log.d("SSL_PINNING_WEBVIEWS", "GET: " + uri.toString());
//
//                try {
//                    // 定义获取的资源流，资源类型，资源编码
//                    InputStream is;
//                    String contentType;
//                    String encoding;
//                    // 设置一个url链接
//                    java.net.URL url = new URL(uri.toString());
//                    // 如果是http请求，这里如果加载的是http请求，则也要建立HttpURLConnection而不是默认加载。
//                    if (uri.toString().startsWith("http:")) {
//                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//                        is = httpURLConnection.getInputStream();
//                        contentType = httpURLConnection.getContentType();
//                        encoding = httpURLConnection.getContentEncoding();
//                    } else { // 如果是https请求
//                        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
//                        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//                        is = urlConnection.getInputStream();
//                        contentType = urlConnection.getContentType();
//                        encoding = urlConnection.getContentEncoding();
//                    }
//
//                    // 如果信息头中的资源类型不为null,则继续
//                    if (contentType != null) {
//
//                        String mimeType = contentType;
//
//                        // 解析出mimeType
//                        if (contentType.contains(";")) {
//                            mimeType = contentType.split(";")[0].trim();
//                        }
//
//                        Log.d("SSL_PINNING_WEBVIEWS", "Mime: " + mimeType);
//
//                        // 返回设置重新设置过的请求
//                        return new WebResourceResponse(mimeType, encoding, is);
//                    }
//
//                } catch (SSLHandshakeException e) {
//                    e.printStackTrace();
//                    Log.d("SSL_PINNING_WEBVIEWS", e.getLocalizedMessage());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    Log.d("SSL_PINNING_WEBVIEWS", e.getLocalizedMessage());
//                }
//
//                // 返回一个空的请求
//                return new WebResourceResponse(null, null, null);
//            }
//
//            private boolean isCause(Class<? extends Throwable> expected, Throwable exc) {
//                return expected.isInstance(exc) || (exc != null && isCause(expected, exc.getCause()));
//            }
        });
        webView.loadUrl(url);
        viewDataBinding.commonTitle.setText(title);
        webView.addJavascriptInterface(new JSInterface(handler), "AndroidJs");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if(null != webView && webView.canGoBack()){
            webView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }
            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.removeAllViews();
            webView.destroy();
        }
        handler = null;
        super.onDestroy();
    }


    /**
     * SSL证书错误，手动校验https证书
     *
     * @param cert      https证书
     * @param sha256Str sha256值
     * @return true通过，false失败
     */
    public static boolean isSSLCertOk(SslCertificate cert, String sha256Str) {
        byte[] SSLSHA256 = hexToBytes(sha256Str);
        Bundle bundle = SslCertificate.saveState(cert);
        if (bundle != null) {
            byte[] bytes = bundle.getByteArray("x509-certificate");
            if (bytes != null) {
                try {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    Certificate ca = cf.generateCertificate(new ByteArrayInputStream(bytes));
                    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
                    byte[] key = sha256.digest(((X509Certificate) ca).getEncoded());
                    return Arrays.equals(key, SSLSHA256);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * hexString转byteArr
     * <p>例如：</p>
     * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }
     *
     * @param hexString
     * @return 字节数组
     */
    public static byte[] hexToBytes(String hexString) {

        if (hexString == null || hexString.trim().length() == 0)
            return null;

        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] bytes = new byte[length];
        String hexDigits = "0123456789abcdef";
        for (int i = 0; i < length; i++) {
            int pos = i * 2; // 两个字符对应一个byte
            int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
            int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
            if (h == -1 || l == -1) { // 非16进制字符
                return null;
            }
            bytes[i] = (byte) (h | l);
        }
        return bytes;
    }



    public class JSInterface {
        private final Handler handler;

        public JSInterface(Handler handler) {
            this.handler = handler;
        }

        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void close(String tips){
            Message message = handler.obtainMessage(0);
            message.obj = tips;
            handler.sendMessage(message);
        }

        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public String getEncrypt(){
            LogUtils.d("获取key", reportKey);
            return reportKey;
        }
    }
}